'use client';

import { KeyInfo } from "@/src/types/types";
import { Input } from "@chakra-ui/react";
import { useEffect, useRef, useState, forwardRef, useImperativeHandle } from "react";

// 导出接口，使组件可被重置
export interface KeyInputRef {
    reset: () => void;
    setKey: (keyInfo: KeyInfo) => void;
}

const KeyInput = forwardRef<KeyInputRef, {onChange: (key: KeyInfo) => void}>(
    ({ onChange }, ref) => {
    
    const inputRef = useRef<HTMLInputElement>(null);
    const [key, setKey] = useState<KeyInfo>({keyName: ''} as KeyInfo);

    // 重置输入框
    const reset = () => {
        setKey({keyName: ''} as KeyInfo);
    };

    // 向父组件公开方法
    useImperativeHandle(ref, () => ({
        reset,
        setKey: (keyInfo: KeyInfo) => {
            setKey(keyInfo);
            // 同时触发onChange回调，保持一致性
            onChange(keyInfo);
        }
    }), [onChange]);
    
    useEffect(() => {
        console.log("KeyInput: key", key);
    }, [key]);

    // 特殊键映射表
    const specialKeyMap: Record<string, string> = {
        'Space': 'SPACE',
        ' ': 'SPACE',
        'Tab': 'TAB',
        'Enter': 'ENTER',
        'Escape': 'ESC',
        'ArrowUp': 'UP',
        'ArrowDown': 'DOWN',
        'ArrowLeft': 'LEFT',
        'ArrowRight': 'RIGHT',
        'Home': 'HOME',
        'End': 'END',
        'PageUp': 'PGUP',
        'PageDown': 'PGDN',
        'Delete': 'DEL',
        'Insert': 'INS',
        'Backspace': 'BKSP'
    };

    const keyDown = (event: any) => {
        event.preventDefault(); // 阻止默认行为
        
        // 获取正确的按键名称
        // let keyName = '';
        // if (event.code === 'Space') {
        //     keyName = 'SPACE'; // 确保空格键显示为"SPACE"
        // } else if (event.code in specialKeyMap) {
        //     keyName = specialKeyMap[event.code];
        // } else if (event.key in specialKeyMap) {
        //     keyName = specialKeyMap[event.key];
        // } else {
        //     keyName = event.key.toUpperCase();
        // }
        
        // const newKey = {
        //     index: key.index,
        //     keyValue: key.keyValue,
        //     keyName: keyName,
        //     type: 0x2,
        //     code1: 0,
        //     code2: eventCode2Keycode(event.code),
        //     code3: 0,
        //     lang: ""
        // }
        // setKey(newKey);
        // onChange(newKey);
    }
    
    useEffect(() => {
        const currentRef = inputRef.current;
        if (currentRef) {
            currentRef.addEventListener('keydown', keyDown);
            
            // 确保获得焦点
            currentRef.focus();
        }
        
        return () => {
            if (currentRef) {
                currentRef.removeEventListener('keydown', keyDown);
            }
        }
    }, []);

    return (
        <Input 
            ref={inputRef} 
            value={key?.keyName || ''} 
            height={"3rem"} 
            w={"18rem"} 
            className="keyinput-box" 
            readOnly={true}
            borderColor="#FF9600"
            borderWidth="2px"
            _hover={{ borderColor: "#FF9600" }}
            _focus={{ borderColor: "#FF9600", boxShadow: "0 0 0 1px #FF9600" }}
        />
    );
});

// 添加组件显示名称，方便调试
KeyInput.displayName = 'KeyInput';

export default KeyInput;